package threadTest;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class ThreadHomeworkSendBuffer {

	private static Queue<Integer> queue = new LinkedList<Integer>();

	public static void main(String[] args) {
		ConsumerBuffer consumerBuffer = new ConsumerBuffer(queue);
		ProducerBuffer producerBuffer = new ProducerBuffer(queue);
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入缓存区大小：");
		int buffer = sc.nextInt();
		if (buffer < 1)
			System.out.println("缓存区不能小于1");
		producerBuffer.setInputbuffer(buffer);
		sc.close();
		new Thread(consumerBuffer).start();
		new Thread(producerBuffer).start();
	}

}

class ProducerBuffer implements Runnable {

	private Queue<Integer> q;
	private int inputbuffer = 1;

	public int getInputbuffer() {
		return inputbuffer;
	}

	public void setInputbuffer(int inputbuffer) {
		if (inputbuffer > 0)
			this.inputbuffer = inputbuffer;
	}

	public ProducerBuffer(Queue<Integer> q) {
		super();
		this.q = q;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Producer start ......");
		for (int i = 0; i < 100; i++) {
			synchronized (q) {
				q.add(i);
				System.out.println("producer....." + i + "   现在缓存里有数据：" + q.size());
				q.notify();
				if (q.size() >= this.inputbuffer) {
					try {
						q.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		}
	}

}

class ConsumerBuffer implements Runnable {

	private Queue<Integer> q;

	public ConsumerBuffer(Queue<Integer> q) {
		super();
		this.q = q;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Consumer start ......");
		for (int i = 0; i < 100; i++) {
			synchronized (q) {
				if (q.isEmpty()) {
					try {
						q.wait();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				int x = q.remove();
				System.out.println("consumer......." + x + "   现在缓存里有数据：" + q.size());
				q.notify();
			}
		}
	}

}